package com.quartz.monitor4job.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

@Slf4j
public class ApplicationUtil {

	private static ApplicationContext applicationContext;

	public static void setApplicationContext(
			ApplicationContext applicationContext) {
		synchronized (ApplicationUtil.class) {
			log.info("setApplicationContext, notifyAll");
			ApplicationUtil.applicationContext = applicationContext;
			ApplicationUtil.class.notifyAll();
		}
	}

	public static ApplicationContext getApplicationContext() {
		synchronized (ApplicationUtil.class) {
			while (applicationContext == null) {
				try {
					log.info("getApplicationContext, wait...");
					ApplicationUtil.class.wait(5 * 60 * 1000);
					if (applicationContext == null) {
						log.warn(
								"Have been waiting for ApplicationContext to be set for 5 minute",
								new Exception());
					}
				} catch (InterruptedException ex) {
					log.warn("getApplicationContext, wait interrupted");
				}
			}
			return applicationContext;
		}
	}

	/**
	 * 这是一个便利的方法，帮助我们快速得到一个BEAN
	 * 
	 * @param beanName
	 *            bean的名字
	 * @return 返回一个bean对象
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanName) {
		return (T)applicationContext.getBean(beanName);
	}
	
   // add by sgh
	public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }
}
